package com.kingsoft.miot.bridge.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kingsoft.miot.bridge.common.CommonResult;
import com.kingsoft.miot.bridge.controller.req.HotelForm;
import com.kingsoft.miot.bridge.controller.req.HotelInfoUpdateBody;
import com.kingsoft.miot.bridge.controller.req.HotelMangerPermissionReq;
import com.kingsoft.miot.bridge.controller.req.HotelReqBody;
import com.kingsoft.miot.bridge.controller.req.ManagerReqBody;
import com.kingsoft.miot.bridge.controller.resp.HotelInfoDetailResp;
import com.kingsoft.miot.bridge.controller.resp.HotelInfoResp;
import com.kingsoft.miot.bridge.controller.resp.HotelInfoRoleResp;
import com.kingsoft.miot.bridge.controller.resp.PageResult;
import com.kingsoft.miot.bridge.controller.tmp.Device;
import com.kingsoft.miot.bridge.controller.tmp.DeviceStatus;
import com.kingsoft.miot.bridge.pojo.hotel.HotelInfo;
import com.kingsoft.miot.bridge.pojo.manager.ManagerInfo;
import com.kingsoft.miot.bridge.service.HotelService;
import com.kingsoft.miot.bridge.service.manager.ManagerService;
import com.kingsoft.miot.bridge.utils.ValidationUtils;

/**
 * 酒店 hotel
 *
 * @author HUJIANQING
 */
@RestController
public class HotelController {

    private static final Logger LOGGER = LoggerFactory.getLogger(HotelController.class);
    // 创建新账号服务
//	@Autowired
//	private AccountService accountService;
    // 酒店
    @Autowired
    private HotelService hotelService;
    // 管理者
    @Autowired
    private ManagerService managerService;
    // 设备服务信息
//	@Autowired
//	private DeviceService deviceService;

    /**
     * 创建酒店 并与相关的authid 相关
     *
     * @return
     */
    @RequestMapping(value = "/addUnitid")
    public String add() {
        String authId = "17309038516633600";
//		accountService.controlUnit(authId);
        return "";
    }

    /**
     * 创建酒店
     *
     * @param hotelForm
     * @return
     */
    @RequestMapping(value = "/data/hotels/create_hotel", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String createHotle(@RequestBody HotelForm hotelForm) {

        HotelInfo hotelInfo = null;
        try {
            // 0. 验证数据
            if (hotelForm == null) {
                return CommonResult.returnJson(false, 400, "接受数据为空，创建酒店失败。");
            }
            ValidationUtils.validate(hotelForm);
        } catch (Exception e) {
            return CommonResult.returnJson(false, 400, "校验数据失败。");
        }
        try {
            // 1. 先获取auth unit id 列表中随机获取一个未被使用的 auth id
//			int auth_unit_id = Integer.valueOf(accountService.controlUnit("17309038516633600"));
            long auth_unit_id = 17309038516633600L;
            // 2. 设置相关数据
            List<String> manager_list = hotelForm.getManager_list();
            hotelInfo = new HotelInfo();
            hotelInfo.setAuth_unit_id(auth_unit_id);
            hotelInfo.setArea_info_name(hotelForm.getArea());
            hotelInfo.setHotel_info_floors_total_num(hotelForm.getFloors_total_num());
            hotelInfo.setHotel_info_managers(JSON.toJSONString(manager_list));
            hotelInfo.setHotel_info_name(hotelForm.getName());
            hotelInfo.setHotel_info_house_total_num(hotelForm.getHouse_total_num());
            hotelInfo.setHotel_info_use_status((short) 1);
            hotelInfo.setHotel_info_create(new Date());
            hotelInfo.setHotel_info_update(new Date());
            // 3.新增数据
            hotelService.insertOne(hotelInfo);
        } catch (Exception e) {
//			e.printStackTrace();
            LOGGER.error("新增数据失败。");
            return CommonResult.returnJson(false, 500, "新增数据失败。");
        }
        return CommonResult.returnJson(true, 200, "新增数据成功。");
    }

    /**
     * 通过id获取hotel详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getHotelInfoById(@PathVariable String id) {
        if (StringUtils.isBlank(id)) {
            LOGGER.info("hotel_id 不能为空");
            return CommonResult.jsonString();
        }
        HotelInfoDetailResp hotelInfoDetailResp = null;
        try {
            hotelInfoDetailResp = hotelService.getHotelInfoDetailResp(Integer.valueOf(id));
            if (hotelInfoDetailResp != null) {
                return CommonResult.jsonString(hotelInfoDetailResp);
            }
        } catch (Exception e) {
            LOGGER.error("获取酒店详细信息失败。");
            return CommonResult.returnJson(false, 500, "获取酒店详细信息失败。");
        }
        return CommonResult.returnJson(false, 200, "获取酒店详细信息失败。");
    }

    /**
     * 当前还没有用到登录 模块 暂时获取全部数据
     * <p>
     * 分页查询酒店
     *
     * @param search
     * @return
     */
    @RequestMapping(value = "/data/hotels", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getHotelListByPage(@RequestBody HotelReqBody pageRequest) {
        if (pageRequest == null) {
            return CommonResult.returnJson(false, 400, "请求数据失败，请求信息为空。");
        }
        try {
            ValidationUtils.validate(pageRequest);
        } catch (Exception e) {
            return CommonResult.returnJson(false, 500, "请求数据失败，请求信息为空。");
        }
        // 1. 获取集团信息
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("corporation_id", 10001);
        dataMap.put("corporation_name", "华住集团");
        dataMap.put("hotel_counts", 3);
        dataMap.put("house_nums", 500);
        dataMap.put("device_nums", 1234);
        dataMap.put("online_device", 100);
        dataMap.put("corporation_admin", "ksc@kingsoft.com");
        // 判断是否为单查询
        if (NumberUtils.isDigits(pageRequest.getSearch())) {
            PageResult<HotelInfoResp> pageResult = hotelService
                    .getByAuthUnitId(Integer.valueOf(pageRequest.getSearch()));
            pageResult.setCorporation_info(dataMap);
            if (pageResult.getItem_list() == null || pageResult.getItem_list().size() <= 0) {
                return JSON.toJSONString(pageResult);
            }
            return JSON.toJSONString(pageResult);
        }
        // 多查询
        int currentPage = pageRequest.getPage();
        int size = pageRequest.getSize();
        PageResult<HotelInfoResp> result = hotelService.findHotelByPage(currentPage, size);
        result.setCorporation_info(dataMap);
        return JSON.toJSONString(result);
    }

    /**
     * 更新酒店信息
     *
     * @param id
     * @param reqBody
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/edit_hotel", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String updateHotel(@PathVariable String id, @RequestBody HotelInfoUpdateBody reqBody) {
        if (!NumberUtils.isDigits(id)) {
            LOGGER.warn("酒店ID: " + id);
            return CommonResult.returnJson(false, 400, "请求参数为空");
        }
        try {
            ValidationUtils.validate(reqBody);
        } catch (Exception e) {
            return CommonResult.returnJson(false, 400, "请求体校验未通过。");
        }
        // 查询并更新数据
        try {
            HotelInfo hotelInfo = hotelService.getById(Integer.valueOf(id));
            hotelInfo.setHotel_info_name(reqBody.getName());
            hotelInfo.setHotel_info_house_total_num(reqBody.getHouse_total_num());
            hotelInfo.setHotel_info_floors_total_num(reqBody.getFloors_total_num());
            int flag = hotelService.updateHotelInfoById(hotelInfo);
            if (flag == 1) {
                return CommonResult.returnJson(true, 200, "数据更新成功。");
            } else {
                return CommonResult.returnJson(false, 200, "数据更新失败。");
            }
        } catch (Exception e) {
            return CommonResult.returnJson(false, 500, "更新酒店数据失败。");
        }
    }

    /**
     * 暂停酒店服务 逻辑暂停
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/operate_hotel", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String pauseOrStartHotel(@PathVariable String id, @RequestBody Map<String, Object> argMap) {
        if (!NumberUtils.isDigits(id) || argMap.size() == 0) {
            LOGGER.error("酒店操作失败，参数为空。");
            return CommonResult.returnJson(false, 400, "酒店操作失败，输入参数为空。");
        }
        try {
            Object obj = argMap.get("status");
            String status = obj.toString();
            Short statusCode = Short.valueOf(status);
            hotelService.pauseOrStartHotelById(Integer.valueOf(id), statusCode);
            if (0 == statusCode) {
                return CommonResult.returnJson(true, 200, "暂停酒店成功");
            } else if (1 == statusCode) {
                return CommonResult.returnJson(true, 200, "启用酒店成功");
            } else {
                return CommonResult.returnJson(false, 400, "操作失败，非法操作代码！");
            }
        } catch (Exception e) {
            return CommonResult.returnJson(false, 500, "暂停酒店使用失败");
        }

    }

    /**
     * 给酒店添加管理者 为相关的酒店 添加管理者 需要管理者具有添加管理者的权限
     *
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/add_manager", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String addManagerToHotel(@PathVariable String id, @RequestBody ManagerReqBody managerReqBody) {
        if (!NumberUtils.isDigits(id)) {
            LOGGER.error("删除酒店管理人员失败");
            return CommonResult.returnJson(false, 400, "删除酒店管理人员失败。");
        }
        // 0. 校验管理者是否和法
        try {
            ValidationUtils.validate(managerReqBody);
            ManagerInfo managerInfo = managerService.getByEmail(managerReqBody.getManager());
            if (managerInfo == null) {
                return CommonResult.returnJson(false, 400, "添加管理员失败");
            }
            // 1. 权限校验
            // 2. 添加数据
            hotelService.addHotelManager(Integer.valueOf(id), managerReqBody.getManager());
            return CommonResult.returnJson(true, 200, "添加酒店管理员成功");
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.returnJson(false, 500, "系统内部错误");
        }

    }

    /**
     * 查询酒店管理人员列表以及权限
     *
     * @return
     */
    @RequestMapping(value = "/data/hotels/{id}/managers", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    public String getHotelManagerAndPermission(@PathVariable String id,
                                               @RequestBody HotelMangerPermissionReq hotelMangerPermissionReq) {
        if (!NumberUtils.isDigits(id)) {
            LOGGER.error("获取酒店员工及权限信息失败。");
            return CommonResult.returnJson(false, 400, "获取酒店员工及权限信息失败。");
        }
        try {
            ValidationUtils.validate(hotelMangerPermissionReq);
        } catch (Exception e) {
            return CommonResult.returnJson(false, 400, "获取酒店失败。");
        }
        try {
            HotelInfo hotelInfo = hotelService.getById(Integer.valueOf(id));
            if (hotelInfo == null) {
                return CommonResult.returnJson(false, 400, "获取酒店管理人员失败，无次酒店。");
            }
            HotelInfoRoleResp resp = managerService.getByHotelInfoId(hotelMangerPermissionReq.getPage(),
                    hotelMangerPermissionReq.getSize(), Integer.valueOf(id));
            return JSON.toJSONString(resp);
        } catch (Exception e) {
            return CommonResult.returnJson(false, 500, "查询酒店信息失败");
        }
    }

}
